<?php

/**
 * sfUserExt.
 *
 * @package    viajemoz
 * @subpackage lib
 * @author     Jonathan Olger Nieto Lajo <jonathan_nieto@hotmail.com>
 */
class sfUserExt extends sfBasicSecurityUser
{
  protected
    $dateTimeFormatter = null,
    $numberFormatter   = null;
    
  public function initialize(sfEventDispatcher $dispatcher, sfStorage $storage, $options = array())
  {
    parent::initialize($dispatcher, $storage, $options);
    
    $this->dateTimeFormatter = new sfDateFormatExt($this->culture);
    $this->numberFormatter   = new sfNumberFormat($this->culture);
  }

  /**
   * @return sfDateFormatExt
   */
  public function getDateTimeFormatter()
  {
    return $this->dateTimeFormatter;
  }
  /**
   * @return sfNumberFormat
   */
  public function getNumberFormatter()
  {
    return $this->numberFormatter;
  }
  
  public function setAuthenticated($authenticated)
  {
    if ($this->options['logging'])
    {
      $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('User is %sauthenticated', $authenticated === true ? '' : 'not '))));
    }
    
    $user = Doctrine::getTable('Usuario')->find($this->getUsuarioId());
    if ($user)
    {
      $user->setLastAccessAt($this->dateTimeFormatter ? $this->dateTimeFormatter->getCurrentDateTime() : date('Y-m-d H:i:s'));
  	  $user->save();
    }
    
    if ($authenticated === true)
    {
      $this->authenticated = true;
      $this->mapPermissions();
    }
    else
    {
      $this->authenticated = false;
      $this->clearCredentials();
      
      //AGREGAR NAMESPACES USADOR POR EL USUARIO
  	  $this->getAttributeHolder()->removeNamespace(sfActionsExt::ERROR_NAMESPACE);
  	  $this->getAttributeHolder()->removeNamespace(sfActionsExt::GENERAL_NAMESPACE);
  	  $this->getAttributeHolder()->removeNamespace(sfActionsExt::PERFIL_NAMESPACE);
  	  $this->getAttributeHolder()->removeNamespace(sfActionsExt::USUARIO_NAMESPACE);
    }
    
    $this->storage->regenerate(false);
  }
  
  public function isAuthenticated()
  {
    return $this->authenticated;
  }
  
  public function logIn(Usuario $user)
  {
    //$fullname = sprintf('%s, %s', $user->getLastName(), $user->getFirstName());
    $this->setAttribute('usuario_id'       , $user->getId()                , sfActionsExt::USUARIO_NAMESPACE);
    $this->setAttribute('login_usuario'    , $user->getLogin()             , sfActionsExt::USUARIO_NAMESPACE);
    $this->setAttribute('perfil_usuario'   , $user->getNombrePerfil()      , sfActionsExt::USUARIO_NAMESPACE);
    $this->setAuthenticated(true);
  }
  
  public function getUsuarioId()
  {
  	return $this->getAttribute('usuario_id'          , null, sfActionsExt::USUARIO_NAMESPACE);
  }
  public function getUsuarioLogin()
  {
  	return $this->getAttribute('login_usuario'       , null, sfActionsExt::USUARIO_NAMESPACE);
  }
  public function getUserPerfil()
  {
  	return $this->getAttribute('perfil_usuario'     , null, sfActionsExt::USUARIO_NAMESPACE);
  }
  
  public function getCurrentRouteName()
  {
  	return $this->getAttribute('current_route_name');
  }
  public function getPermissions()
  {
  	return $this->getAttribute('permissions'      , null, sfActionsExt::USUARIO_NAMESPACE);
  }
  
  protected function mapPermissions()
  {
  	$usuario = Doctrine::getTable('Usuario')->find($this->getUsuarioId());
  	//Deb::print_r($this->getUsuarioId());
  	$permissions = array();
  	$acciones = $usuario->getAcciones();
  	
  	foreach ($acciones as $accion)
  	{
  	  $permissions[$accion->getRuta()] = array();
  	}
  	
  	$this->setAttribute('permissions', $permissions, sfActionsExt::USUARIO_NAMESPACE);
  }
  
  public function hasPermissions($route_names, $strict = false)
  {
  	foreach ($route_names as $route_names)
  	{
  	  if ($this->hasPermission($route_names))
  	  {
  	  	if (!$strict)
  	  	{
  	  	  return true;
  	  	}
  	  }
  	  else
  	  {
  	  	if ($strict)
  	  	{
  	  	  return false;
  	  	}
  	  }
  	}
  	
  	if ($strict)
  	{
  	  return true;
  	}
  	else
  	{
  	  return false;
  	}
  }
  public function hasPermission($route_name)
  {
  	$route_name = trim($route_name, '@');
  	$routes = sfContext::getInstance()->getRouting()->getRoutes();
  	
  	// FIXME: sfRoute protected parameters
  	/*if (isset($routes[$route_name]))
  	{
  	  $route  = $routes[$route_name];
  	  $secure = isset($route[3]['secure']) ? $route[3]['secure'] : true;
  	}
  	else
  	{
  	  $secure = true; // order_edit_XX_XX
  	}*/
  	$secure = false;  // david tataje cambiat
  	
  	$permissions = $this->getPermissions();
  	if (!$secure || isset($permissions[$route_name]))
  	{
  	  return true;
  	}
  	
  	return false;
  }
}
